package com.cip.webapp.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cip.admin.model.User;
import com.cip.common.util.SecurityUtil;


public class UserCacheFilter implements Filter {

	/**
	 * This method is used destroy
	 */
	public void destroy() {
	}

	/**
	 * This method is used to do filter.
	 * 
	 * @param req
	 *            - a ServletRequest object
	 * @param res
	 *            - a ServletResponse object
	 * @param chain
	 *            DOCUMENT ME!
	 * 
	 * @throws IOException
	 *             DOCUMENT ME!
	 * @throws ServletException
	 *             DOCUMENT ME!
	 */
	public final void doFilter(final ServletRequest req,
			final ServletResponse res, final FilterChain chain)
			throws IOException, ServletException {		
		HttpServletRequest httpRequest = (HttpServletRequest) req;
		HttpSession session = httpRequest.getSession();
		
		User user = (User)session.getAttribute("user");
		if ( user != null) {
			SecurityUtil.getThreadLocalUser().set(user);
		}else {
			//System.out.println("user info not in session, first time? ..............................");
		}
		chain.doFilter(req, res);
		// for the very first time we need to set it in session	
		/*try {
			//set the user details in cache only if session is valid
			//looks like radlogin.action is invalidating session in a scenario
			httpRequest.getSession();
		} catch (Exception e) {
			return;
		}*/	
		if (httpRequest.isRequestedSessionIdValid() && session.getAttribute("user") == null) {
			if (SecurityUtil.getThreadLocalUser() == null) {
				throw new RuntimeException(
						"User is null in session as well as thread local");
			}
			session.setAttribute("user",
					SecurityUtil.getThreadLocalUser().get());
		}	
		// clean up defensivly to ensure garbage collection
		SecurityUtil.getThreadLocalUser().remove();
	}

	/**
	 * This method is used to initialize
	 * 
	 * @param filterConfig
	 *            - a FilterConfig object
	 * 
	 * @throws ServletException
	 *             DOCUMENT ME!
	 */
	public void init(final FilterConfig filterConfig) throws ServletException {
	}
}

